#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
from ..._util import Util, CopiedAndSymlinkedDir
from ..._game import GameBase, GameSpec, MatchContext
from ..._game_straits import GameStraitForWindows, GameStraitNeedConfigDir


class LocoMania(GameBase, GameStraitForWindows):

    def __init__(self, data_dir):
        GameBase.__init__(self, data_dir)

        self._addStrait(GameStraitNeedConfigDir())

        self._spec = GameSpec()
        if True:
            self._spec.windows_archs = [self.WindowsArch.WIN32]
            self._spec.windows_versions = [self.WindowsVersion.WINXP, "*"]

            self._spec.default_language = "en_US"
            self._spec.languages = [self._spec.default_language]

            self._spec.resolutions = ["640x480"]               # FIXME
            self._spec.can_fullscreen = False                  # FIXME
            self._spec.can_windowed = True

    @property
    def spec(self):
        return self._spec

    @property
    def run_items(self):
        return ["main"]

    def get_title(self, lang):
        return "Loco Mania"

    def _prepare(self, context):
        self._context = context
        try:
            self._targetGameDirObj = CopiedAndSymlinkedDir(os.path.join(self._context.drive_c_dirpath, "Loco Mania"), [self._dataDir])
            self._targetGameDirObj.symlink("", recursive=True)
            # self._targetGameDirObj.restore_from(self._context.config_dirpath, exclude=["game.ini"])
            self._targetGameDirObj.clear()
        except BaseException:
            self._cleanup(on_error=True)
            raise

    @MatchContext.edit_or_run
    def get_language(self):
        return self._spec.default_language

    @MatchContext.edit_or_run
    def set_language(self, language):
        assert language == self._spec.default_language

    @MatchContext.run
    def apply_resolution(self, resolution):
        assert resolution == "640x480"

    @MatchContext.run
    def apply_fullscreen_or_windowed(self, fullscreen_or_windowed):
        assert not fullscreen_or_windowed

    def _commit(self):
        pass

    def _getRunInfo(self, item):
        assert not self._context.edit_or_run
        assert item == Util.listGetOnlyItem(self.run_items)

        return self.RunInfo("C:\\Loco Mania\\start.exe")

    def _cleanup(self, on_error=False):
        if hasattr(self, "_targetGameDirObj"):
            if not on_error:
                pass
            del self._targetGameDirObj
        if hasattr(self, "_context"):
            del self._context

# # create or flush user settings file
# if [ ! -e "$CFGDIR/Save" ] ; then
#     mkdir -p "$CFGDIR/Save"
# fi
# "${GAMEDIR}/cfg2settings" "$(id -un)" "$CFGDIR"
# ln -sf "$CFGDIR/Save/settings.dat" "$DATADIR/drive_c/Loco Mania/lm/data/$(id -un)_settings.dat"

# # run the game
# cd "$DATADIR/drive_c/Loco Mania"
# WINEPREFIX="$DATADIR" wine GO.EXE -module lm -lang en

# # modify user settings file
# file_to_symlink "$DATADIR/drive_c/Loco Mania/lm/data/$(id -un)_settings.dat" "$CFGDIR/Save/settings.dat"
# file_to_symlink "$DATADIR/drive_c/Loco Mania/lm/data/$(id -un)_scores.dat" "$CFGDIR/Save/scores.dat"
# file_to_symlink "$DATADIR/drive_c/Loco Mania/lm/data/config.sc" "$CFGDIR/Save/config.sc"
# file_to_symlink "$DATADIR/drive_c/Loco Mania/lm/data/tutorial.save" "$CFGDIR/Save/tutorial.save"

# src_unpack() {
# 	unzip "${DISTDIR}/Loco.Mania.zip" -d "${WORKDIR}"
# 	mv "${WORKDIR}/Loco Mania" "${WORKDIR}/install"

# 	mkdir "${WORKDIR}/Loco Mania"
# 	cd "${WORKDIR}/Loco Mania"
# 	mv "${WORKDIR}/install/TNT.UHA" .
# 	uharc x -y+ TNT.UHA
# 	rm -f TNT.UHA

# 	rm -rf "${WORKDIR}/install"
# }

# src_install() {
# 	dodir "opt/${PN}"
# 	cp -r "Loco Mania" "${D}/opt/${PN}"
# 	cp -r "${FILESDIR}/cfg2settings" "${D}/opt/${PN}"

# 	dobin "${PN}"
# #	doicon "${FILESDIR}/${PN}.png"
# 	domenu "${FILESDIR}/${PN}.desktop"
# }

# https://github.com/XeNTaXBackup/XeNTaXBackup.github.io/blob/2c6074a1bcb085e77f527fcf620620a4ee1e76da/markdown/Loco%20Mania%20%20Locomania_2121.md?plain=1#L7

# The subdirectory ".\lm\data" contains the levels
# 3 files for each - for example Level 2:
# level002.dat - ASCII file, contains a hash/checksum (?) for the data file and some parameters regarding gameplay (maximum count of trains etc.)
# level002.pkg - binary file, big (10 - 25 MB), seems to contain the mesh data for the landscape of the level, the magic word at the beginning is "#LF2PKG:"
# level002.sc - ASCII file, contains parameters for the graphical representation (like fog density etc.)

# Unfortunately, the change of even a single value (like 12 instead of 10 maximum train count) in the ASCII files causes the game to not even start (jumps back to the desktop immediately), so I pretend that the hash in the DAT-file is taken as a checksum.

# Also, I would want to know how the mesh data of the landscape is stored in the PKG file.

# Does anybody has a clue, is already on it, or in need of a challenge?!   
